<?php

if (!defined('ABSPATH')) exit; // Exit if accessed directly

/**
 * Plugin Name: WooCommerce CustomPay Gateway
 * Plugin URI: https://www.custompay.io/
 * Description:  Provides a custompay.io Payment Gateway.
 * Author: bropay.io
 * Author URI: https://www.custompay.io/
 * Version: 1.0.0
 * Text Domain: custompay
 * replace custompay to make your own gateway
 */

add_action( 'plugins_loaded', 'custompay_gateway_load', 0 );

//write a class to load custom gateway plugin
function custompay_gateway_load() {

    //if woocommerce is not loaded, return
    if ( ! class_exists( 'WC_Payment_Gateway' ) ) {
        return;
    }

    /**
     * Add the custompay gateway to the WooCommerce.
     */
    add_filter( 'woocommerce_payment_gateways', 'wc_custompay_add_gateway' );


    //write class WC_Gateway_Bropay to extend WC_Payment_Gateway, if the class does not exist, just create it
    function wc_custompay_add_gateway( $methods ) {
        if (!in_array('WC_Gateway_Custompay', $methods)) {
            $methods[] = 'WC_Gateway_Custompay';
        }
        return $methods;
    }

    class WC_Gateway_Custompay extends WC_Payment_Gateway {

        //call back url
        public $callback_url;

        /**
         * constructor for the gateway
         */

        public function __construct(){
            $this->id = 'custompay';

            //icon of the payment gateway
            $this->icon = apply_filters('woocommerce_custompay_icon', '');
            //this applies to the gateway that has its fields in the checkout form if sets to true
            $this->has_fields = false;

            //Title of the payment method shown on the admin page.
            $this->method_title = __('CustomPay', 'custompay');

            //Description for the payment method shown on the admin page.
            $this->method_description = __('CustomPay Payment Gateway', 'custompay');
            $this->supports = array(
                'products'
            );

            //define payment settings fields
            $this->init_form_fields();

            //After init_settings() is called, you can get the settings and load them into variables
            $this->init_settings();

            $this->title = $this->get_option('title');
            $this->description = $this->get_option('description');
            $this->callback_url = home_url('wc-api/custompay-callback/');
            add_action( 'woocommerce_api_callback', array($this, 'callback_handler'));
            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        }

        /**
         * Initialize Gateway Settings Form Fields
         */

        public function init_form_fields() {

            $this->form_fields = array(
                'enabled' => array(
                    'title' => __('Enable/Disable', 'custompay'),
                    'type' => 'checkbox',
                    'label' => __('Enable CustomPay Payment Gateway', 'custompay'),
                    'default' => 'no'
                ),
                'title' => array(
                    'title' => __('Title', 'custompay'),
                    'type' => 'text',
                    'description' => __('This controls the title which the user sees during checkout.', 'custompay'),
                    'default' => __('CustomPay Payment Gateway', 'custompay'),
                    'desc_tip' => true,
                ),
                'description' => array(
                    'title' => __('Description', 'custompay'),
                    'type' => 'textarea',
                    'description' => __('This controls the description which the user sees during checkout.', 'custompay'),
                    'default' => __('Pay securely using CustomPay.', 'custompay'),
                ),
                'api_key' => array(
                    'title' => __('API Key', 'custompay'),
                    'type' => 'text',
                    'description' => __('This is the API key provided by CustomPay when you signed up for an account.', 'custompay'),
                    'default' => '',
                    'desc_tip' => true,
                ),
                'merchant' => array(
                    'title' => __('Merchant ID', 'custompay'),
                    'type' => 'text',
                    'description' => __('This is the merchant ID provided by CustomPay when you signed up for an account.', 'custompay'),
                    'default' => '',
                    'desc_tip' => true,
                ),
            );
        }

        function process_payment($order_id)
        {
            global $woocommerce;
            $order = new WC_Order( $order_id );


            //$order->update_status('on-hold', _( 'Awaiting cheque payment', 'woocommerce' ));

            $woocommerce->cart->empty_cart();

            return array(
                 'result' => 'success',
                 'redirect' => $this->get_payment_gateway_redirect_url($order)
           );
        }

        function callback_handler()
        {
//            $order_id = $_GET['order_id'];
//            $order = wc_get_order($order_id);
//            $order->update_status('completed');
//            $order->payment_complete();
//            $order->reduce_order_stock();
//            $order->save();
        }

        //write your own function to post data to the payment gateway and get redirect url
        function get_payment_gateway_redirect_url($order):string
        {
            //get ordered products and put them into cart items array
            foreach($order->get_items() as $item){
                $product = $item->get_product();
                $active_price   = $product->get_price();
                $product_name   = $product->get_name();
                $item_quantity  = $item->get_quantity();
                $sku = $product->get_sku();
                $cart_items_array[] = ["name" => $product_name, "price" => $active_price, "quantity" => $item_quantity, "sku" => $sku];
            }

            $args = [
                "amount" => $order->get_total(),
                "currency" => $order->get_currency(),
                "success_url" => $this->get_return_url( $order ),
                "cancel_url" => esc_url_raw($order->get_cancel_order_url_raw()),
                "notify_url" => $this->callback_url,
            ];

            return "third party payment gateway url";
        }

    }

}
